<template>
	<view class="container">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText"></block>
			<block slot="content">合同编辑</block>
		</cu-custom>

		<view class="margin-top" style="background-color: white; padding-left: 40rpx; padding-right: 40rpx;">
			<u--form
				labelPosition="left"
				labelWidth="80"
				:model="formData"
				:rules="rules"
				ref="uForm"
			>
				<u-form-item
					label="合同名称"
					labelWidth="80"
					prop="contractName"
					borderBottom
				>
					<u-input
						v-model="formData.contractName"
						border="none"
						placeholder="请输入合同名称"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="合同编号"
					labelWidth="80"
					prop="contractCode"
					borderBottom
				>
					<u-input
						v-model="formData.contractCode"
						border="none"
						placeholder="请输入合同编号"
					>
					</u-input>
				</u-form-item>
				<u-form-item
					label="合同类型"
					labelWidth="80"
					prop="type"
					borderBottom
					@click="showType = true;"
				>
					<u--text :text="formData.typeText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="开始日期"
					labelWidth="80"
					prop="beginDate"
					borderBottom
					@click="showStart = true;"
				>
					<u--text :text="startDateFormat"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="结束日期"
					labelWidth="80"
					prop="industry"
					borderBottom
					@click="showEnd = true;"
				>
					<u--text :text="endDateFormat"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="状态"
					labelWidth="80"
					prop="status"
					borderBottom
					@click="showStatus = true;"
				>
					<u--text :text="formData.statusText"></u--text>
					<u-icon
							slot="right"
							name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="附件"
					prop="fileUpload"
					labelWidth="80"
					borderBottom
					labelPosition="left"
				>
					<u-upload
					    v-if="!loading"
						:fileList="formData.fileUpload"
						@afterRead="afterRead"
						@delete="deletePic"
						name="before"
						multiple
						:maxCount="5"
						:previewFullImage="true"
					>
					</u-upload>
				</u-form-item>
			</u--form>
			<u-gap height="30" bgColor="#fff"></u-gap>
			<u-button text="提交" type="primary" @click="submitForm"></u-button>
			<u-gap height="20" bgColor="#fff" v-if="id"></u-gap>
			<u-button text="删除" type="error" @click="deleteForm" v-if="id"></u-button>
			<u-gap height="20" bgColor="#fff"></u-gap>
			<view>
				<u-radio-group v-model="protocol">
					<u-radio shape="circle" label="同意" labelSize="12" name="agree"></u-radio>
					<u--text decoration="underline" text="用户服务及隐私协议" size="13" @click="clickProtocol" type="primary"></u--text>
				</u-radio-group>
			</view>
			<u-gap height="30" bgColor="#fff"></u-gap>
		</view>
		
		<u-picker :show="showStatus" title="选择状态" :columns="statusColumns" :defaultIndex="selectedStatusIndex" keyName="label" :closeOnClickOverlay="true" @confirm="changeStatus" @close="cancelStatus" @cancel="cancelStatus"></u-picker>
		<u-picker :show="showType" title="选择合同类型" :columns="typeColumns" :defaultIndex="selectedTypeIndex" keyName="label" :closeOnClickOverlay="true" @confirm="changeType" @close="cancelType" @cancel="cancelType"></u-picker>
		<u-datetime-picker title="选择开始时间" mode="date":closeOnClickOverlay="true" :show="showStart" v-model="startDate" @confirm="closeStartDate" @close="closeStartDate" @cancel="closeStartDate"></u-datetime-picker>
		<u-datetime-picker title="选择结束时间" mode="date":closeOnClickOverlay="true" :show="showEnd" v-model="endDate" @confirm="closeEndDate" @close="closeEndDate" @cancel="closeEndDate"></u-datetime-picker>
		<u-modal :show="showDelete" title="警告" content="删除后不可恢复,确定要删除吗？" :showCancelButton="true" @confirm="confirmDelete" :closeOnClickOverlay="true" @close="showDelete = false;" @cancel="showDelete = false;"></u-modal>
		<u-popup :show="showProtocol" :closeOnClickOverlay="true" @close="showProtocol = false;">
			<view class="padding">
				<u--text text="用户服务及隐私协议" color="#333333" :bold="true" size="16" align="center"></u--text>
				<u-gap height="10" bgColor="#fff"></u-gap>
				<u--text size="14" lineHeight="30" text="我们致力于保护您在使用我们小程序时所提供的私隐、私人资料以及个人的资料(统称“个人资料”)，使我们在收集、使用、储存和传送个人资料方面符合(与个人资料私隐有关的法律法规)及消费者保护方面的最高标准。 为确保您对我们在处理个人资料上有充分信心，您切要详细阅读及理解隐私政策的条文。"></u--text>
				<u-gap height="8" bgColor="#fff"></u-gap>
				<u--text size="14" lineHeight="30" text="收集个人资料的目的及用途如下:通过我们的小程序向您提供我们的各项服务;当您使用我们的小程序时，能辨认以及确认您的身份;您上报的油烟及隔油池信息将绑定到您填写的商户名下,以便后续与我们结算各项事宜。"></u--text>
				<u-gap height="8" bgColor="#fff"></u-gap>
				<u--text size="14" lineHeight="30" text="感谢您的阅读,我们将竭诚为您服务。"></u--text>
				<u-gap height="15" bgColor="#fff"></u-gap>
			</view>
		</u-popup>
		<!-- 加载弹窗 -->
		<view class="cu-load load-modal" v-if="loading">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<image src="https://mini.wm-mis.com/img/static/car.png" mode="aspectFit" class="round"></image>
			<view class="gray-text">加载中...</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/api'
	import moment from 'moment';
	import {
		mapState
	} from 'vuex';
	import configService from '@/common/service/config.service.js';
	import {ACCESS_TOKEN} from '@/common/util/constants.js'
	
	export default {
		computed: {
			...mapState([
				'dicts'
			]),
			startDateFormat(){
				return moment(Number(this.startDate)).format('YYYY-MM-DD');
			},
			endDateFormat(){
				return moment(Number(this.endDate)).format('YYYY-MM-DD');
			}
		},
		data() {
			return {
				contractDetail: null,
				shopId: null,
				id: '',
				loading: false,
				startDate: (new Date()).getTime(),
				endDate: (new Date()).getTime() + 3 * 365 * 24 * 60 * 60 * 1000,
				showStart: false,
				showEnd: false,
				showStatus: false,
				statusColumns: [],
				selectedStatusIndex: [0],
				showType: false,
				typeColumns: [],
				selectedTypeIndex: [0],
				showDelete: false,
				protocol: "agree",
				showProtocol: false,
				formData: {
					id: '',
					contractName: '',  //合同名称
					type: '',          //合同类型
					typeText: '',      
					contractCode: '',  //合同编号
					beginDate: '',     //开始日期
					endDate: '',       //结束日期
					fkShopId: '',      
					statusText: '',
					status: '',
					fileUpload: []
				},
				rules: {
					'contractName': {
						type: 'string',
						required: true,
						message: '请输入合同名称',
						trigger: ['blur', 'change']
					},
					'contractCode': {
						type: 'string',
						required: true,
						message: '请输入合同编号',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		async onLoad(options){
			this.statusColumns = [this.dicts.contract_status]
			this.typeColumns = [this.dicts.contract_type]
			
			this.shopId = options.shopId
			this.id = options.id
			if(this.id){
				this.formData.id = this.id
				await this.getContractDetail()
				let index2 = 0
				for(let item of this.dicts.contract_status){
					if(this.formData.status == item.value){
						this.selectedStatusIndex = [index2]
						this.formData.statusText = item.label
						break
					}
					index2++
				}
				
				let index3 = 0
				for(let item of this.dicts.contract_type){
					if(this.formData.type == item.value){
						this.selectedTypeIndex = [index3]
						this.formData.typeText = item.label
						break
					}
					index3++
				}
			}
			else{
				//初始化
				this.formData.status = this.dicts.contract_status[0].value
				this.formData.statusText = this.dicts.contract_status[0].label
				this.formData.type = this.dicts.contract_type[0].value
				this.formData.typeText = this.dicts.contract_type[0].label
			}
			this.formData.fkShopId = this.shopId
		},
		methods: {
			async submitForm(){
				let that = this
				that.loading = true
				let res = null
				let temp = JSON.parse(JSON.stringify(this.formData))
				let urlArr = []
				for(let item of temp.fileUpload){
					urlArr.push(item.url.replace(configService.apiUrl + '/sys/common/static/', ''))
				}
				delete temp.fileUpload
				temp.beginDate = this.startDateFormat
				temp.endDate = this.endDateFormat
				temp.attachment = urlArr.join(",");
				if(temp.id){
					res = await api.contractEdit(temp)
				}
				else{
					delete temp.id
					res = await api.contractInsert(temp)
				}
				
				if(res.data.code == 200 && res.data.success){
					uni.setStorageSync('entryDetail', 'contractDetail')//添加操作标记，返回时需要刷新
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
					
					that.loading = false
					setTimeout(()=>{
						uni.navigateBack();
					}, 2000)
				}
				that.loading = false
			},
			async deleteForm(){
				this.showDelete = true
			},
			async confirmDelete(){
				let that = this
				that.showDelete = false
				that.loading = true
				let res = await api.contractDelete({
					id: that.id
				})
				if(res.data.code == 200 && res.data.success){
					uni.setStorageSync('entryDetail', 'contractDetail')//添加操作标记，返回时需要刷新
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 2000
					})
					
					that.loading = false
					setTimeout(()=>{
						uni.navigateBack();
					}, 2000)
				}
				that.loading = false
			},
			async getContractDetail(){
				let that = this
				that.loading = true
				let res = await api.contractDetail({
					id: that.id
				})
				if(res.data.code == 200 && res.data.success){
					that.contractDetail = res.data.result
					that.formData.id = res.data.result.id
					that.formData.contractName = res.data.result.contractName
					that.formData.type = res.data.result.type
					that.formData.contractCode = res.data.result.contractCode
					that.formData.beginDate = res.data.result.beginDate
					that.formData.endDate = res.data.result.endDate
					that.formData.fkShopId = res.data.result.fkShopId
					that.formData.status = res.data.result.status
					if(res.data.result.attachment){
						let temp = []
						let imgArr = res.data.result.attachment.split(",")
						for(let img of imgArr){
							let url = configService.apiUrl + '/sys/common/static/' + img
							temp.push({
								thumb: url,
								url: url
							})
						}
						that.formData.fileUpload = temp
					}
					
					that.startDate = (new Date(that.formData.beginDate)).getTime()
					that.endDate = (new Date(that.formData.endDate)).getTime()
				}
				that.loading = false
			},
			
			async changeStatus(e) {
				const {
					indexs,
					value
				} = e
			
				let that = this;
				that.showStatus = false;
				
				//选中的设备
				let selectIndex = indexs[0];
				let selectStatus = that.dicts.contract_status[selectIndex];
				that.selectedStatusIndex = [selectIndex];
				that.formData.status = selectStatus.value
				that.formData.statusText = selectStatus.label
			},
			cancelStatus() {
				this.showStatus = false;
			},
			async changeType(e) {
				const {
					indexs,
					value
				} = e
			
				let that = this;
				that.showType = false;
				
				//选中的设备
				let selectIndex = indexs[0];
				let selectType = that.dicts.contract_type[selectIndex];
				that.selectedTypeIndex = [selectIndex];
				that.formData.type = selectType.value
				that.formData.typeText = selectType.label
			},
			cancelType() {
				this.showType = false;
			},
			closeStartDate(value){
				this.showStart = false;
			},
			closeEndDate(value){
				this.showEnd = false;
			},
			clickProtocol(){
				this.showProtocol = !this.showProtocol
			},
			// 删除图片
			deletePic(event) {
				this.formData['fileUpload'].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData['fileUpload'].length
				lists.map((item) => {
					this.formData['fileUpload'].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.formData['fileUpload'][fileListLen]
					this.formData['fileUpload'].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: configService.apiUrl + '/sys/common/static/' + result
					}))
			
					fileListLen++
				}
			},
			async uploadFilePromise(url) {
				let header = {
					'X-Access-Token': uni.getStorageSync(ACCESS_TOKEN)
				};
			
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						header: header,
						url: configService.apiUrl + '/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let response = JSON.parse(res.data)
							resolve(response.message)
						}
					});
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	
</style>
